package com.zzyl.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.ObjectUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WeChatServiceImpl implements WeChatService {

    private static final String REQUEST_URL="https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";
    private static final String TOKEN_URL= "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    private static final String PHONE_URL="https://api.weixin.qq.com/wxa/business/getuserphonenumber?";
    @Value("${zzyl.framework.wechat.appId}")
    private String APP_ID;

    @Value("${zzyl.framework.wechat.appSecret}")
    private String APP_SECRET;


    @Override
    public String getOpenId(String code) {
        Map<String,Object> map=new HashMap<>();
        map.put("appid",APP_ID);
        map.put("secret",APP_SECRET);
        map.put("js_code",code);
        String s = HttpUtil.get(REQUEST_URL, map);
        JSONObject Json = JSONUtil.parseObj(s);
        if(ObjectUtil.isNotEmpty(Json.get("errcode"))){//不为空则报错
            throw new RuntimeException((String)Json.get("errmsg"));
        }
        String openid = (String)Json.get("openid");
        return openid;
    }

    @Override
    public String getPhone(String phoneCode) {

        String accessToken = getAccessToken();
        Map<String,Object> map=new HashMap<>();
        map.put("code",phoneCode);


        HttpResponse execute = HttpUtil.createRequest(Method.POST, PHONE_URL + "access_token=" + accessToken).body(JSONUtil.toJsonStr(map)).execute();
        String post =execute.body();

        JSONObject entries = JSONUtil.parseObj(post);
        JSONObject entries1 = JSONUtil.parseObj(entries.get("phone_info"));

        return (String)entries1.get("phoneNumber");

    }

    @Override
    public String getAccessToken() {
        Map<String,Object> map=new HashMap<>();
        map.put("appid",APP_ID);
        map.put("secret",APP_SECRET);
        String s = HttpUtil.get(TOKEN_URL, map);
        JSONObject parse = JSONUtil.parseObj(s);
        return (String)parse.get("access_token");
    }
}
